package edu.pku.sei.mte.serialization;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import edu.pku.sei.mte.exceptions.ExceptionRegistry;
import edu.pku.sei.mte.mtemodel.mtmodel.rulebased.RBTransformation;

public class ExceptionRegistryLoader {
	
	public ExceptionRegistry load(String filename, RBTransformation trans){
		DocumentBuilderFactory factory = null;
		factory = DocumentBuilderFactory.newInstance();
		factory.setIgnoringComments(true);
		factory.setIgnoringElementContentWhitespace(true);
		factory.setNamespaceAware(true);
		File file = new File(filename);
		if(!file.exists()){
			System.out.println("file not exist!");
			return null;
		}
		ExceptionRegistry reg = new ExceptionRegistry();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(file);
			Element root = doc.getDocumentElement();
			NodeList exs = root.getElementsByTagName("exception");
			int length = exs.getLength();
			for(int i=0;i<length;i++){
				Node n = exs.item(i);
				if(n.getNodeType()!=Node.ELEMENT_NODE)
					continue;
				Element ex = (Element) n;
				String exceptionName = ex.getAttribute("name");
				String exceptionFile = ex.getAttribute("file");
				String handlerFile = ex.getAttribute("handler");
				reg.registerException(exceptionName, exceptionFile, handlerFile);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return reg;
	}
	
}
